const int btn_pin = 2; //按键
const int led_pin = 5; //LED灯
int led_state = LOW; //LED灯状态

const int Rheostat = 0; //可调电阻
int sensorValue = 0; //电阻值

const int Relay_01 = 4;//继电器

volatile unsigned long delayTime = 0; //设定时长
volatile unsigned long elapseTime = 0; //已走时长
volatile unsigned long startTime = 0; //开始时间点

void setup() {
  pinMode(btn_pin, INPUT_PULLUP);
  pinMode(led_pin, OUTPUT);
  attachInterrupt(0, toggle, FALLING);

  pinMode(Rheostat, OUTPUT);
  pinMode(Relay_01, HIGH);
  digitalWrite(Relay_01, HIGH);
  
  startTime = millis();
  
  Serial.begin(9600);
}

void loop() {
  delay(1000);
  elapseTime = millis() - startTime;
  if(elapseTime >= delayTime){
    digitalWrite(Relay_01, HIGH);
  }

  Serial.print("elapseTime = ");
  Serial.println(elapseTime);
}

void toggle(){
  led_state = !led_state;
  digitalWrite(led_pin, led_state);
  digitalWrite(Relay_01, HIGH);

  if(led_state == HIGH){    
    sensorValue = 0;
    sensorValue = analogRead(Rheostat);
    sensorValue += analogRead(Rheostat);
    sensorValue += analogRead(Rheostat);

    sensorValue = sensorValue / 3;
    Serial.print("Value = ");
    Serial.println(sensorValue);

    if(sensorValue <= 65) {
      delayTime = 180000;
    } else if(sensorValue > 65 && sensorValue <= 185) {
      delayTime = 900000;
    } else if(sensorValue > 185 && sensorValue <= 315) {
      delayTime = 1800000;
    }else if(sensorValue > 315 && sensorValue <= 435) {
      delayTime = 2700000;
    }else if(sensorValue > 435 && sensorValue <= 565) {
      delayTime = 3600000;
    }else if(sensorValue > 565 && sensorValue <= 685) {
      delayTime = 4500000;
    }else if(sensorValue > 685 && sensorValue <= 815) {
      delayTime = 5400000;
    }else if(sensorValue > 815 && sensorValue <= 935) {
      delayTime = 6300000;
    }else if(sensorValue > 935) {
      delayTime = 7200000;
    }

    Serial.print("delayTime = ");
    Serial.println(delayTime);

    elapseTime = 0;
    startTime = millis();
    digitalWrite(Relay_01, LOW);
  }
}
